<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑包裹配置' : '新增包裹配置'"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="config-form"
    >
      <el-form-item label="包裹类型" prop="packageType">
        <el-input
          v-model="form.packageType"
          placeholder="请输入包裹类型，如：小件、中件、大件等"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="重量范围" prop="weightRange">
        <el-input
          v-model="form.weightRange"
          placeholder="请输入重量范围，如：0-1kg、1-5kg等"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="收费标准" prop="feeStandards">
        <el-input
          v-model="form.feeStandards"
          placeholder="请输入收费标准"
          clearable
          type="number"
          step="0.01"
          min="0"
        >
          <template #append>元</template>
        </el-input>
        <div class="form-tip">
          <el-text type="info" size="small">请输入金额，支持两位小数</el-text>
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createPackageConfig, updatePackageConfig } from '@/api/express'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  configData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  packageType: '',
  weightRange: '',
  feeStandards: ''
})

// 表单验证规则
const rules = reactive({
  packageType: [
    { required: true, message: '请输入包裹类型', trigger: 'blur' },
    { min: 2, max: 20, message: '包裹类型长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  weightRange: [
    { required: true, message: '请输入重量范围', trigger: 'blur' },
    { min: 2, max: 50, message: '重量范围长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  feeStandards: [
    { required: true, message: '请输入收费标准', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入收费标准'))
        } else if (isNaN(Number(value))) {
          callback(new Error('收费标准必须是数字'))
        } else if (Number(value) < 0) {
          callback(new Error('收费标准不能为负数'))
        } else if (Number(value) > 999999.99) {
          callback(new Error('收费标准不能超过999999.99元'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
})

// 监听visible变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal && props.isEdit && props.configData) {
    // 编辑模式，填充数据
    nextTick(() => {
      Object.assign(form, {
        packageType: props.configData.packageType || '',
        weightRange: props.configData.weightRange || '',
        feeStandards: props.configData.feeStandards || ''
      })
    })
  } else if (newVal && !props.isEdit) {
    // 新增模式，重置表单
    resetForm()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    packageType: '',
    weightRange: '',
    feeStandards: ''
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    if (props.isEdit) {
      // 编辑包裹配置
      const submitData = {
        param: {
          id: props.configData.id,
          packageType: form.packageType,
          weightRange: form.weightRange,
          feeStandards: Number(form.feeStandards)
        }
      }

      await updatePackageConfig(submitData)
      ElMessage.success('包裹配置更新成功')
      
      // 关闭对话框并通知父组件刷新列表
      handleClose()
      emit('success')
    } else {
      // 新增包裹配置
      const submitData = {
        param: {
          packageType: form.packageType,
          weightRange: form.weightRange,
          feeStandards: Number(form.feeStandards)
        }
      }

      await createPackageConfig(submitData)
      ElMessage.success('包裹配置创建成功')
      
      // 关闭对话框并通知父组件刷新列表
      handleClose()
      emit('success')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.config-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-form-item {
  margin-bottom: 24px;
}

.form-tip {
  margin-top: 4px;
  line-height: 1.4;
}

/* 表单项标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: box-shadow 0.2s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 数字输入框样式 */
:deep(.el-input-number .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

/* 输入框后缀样式 */
:deep(.el-input-group__append) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #909399;
  font-weight: 500;
}
</style>
